
#include "StdAfx.h"
#include "LogService.h"
#include "StringObj.h"
#include <tinyxml.h>

#ifdef WIN32
#pragma comment( lib, "tinyxml.lib" )
#endif

LogService::LogService(){
	emergency_ = new CLog( CLog::LOG_TYPE_CONSOL | CLog::LOG_TYPE_FILE, "log", \
		"emergency_log.txt", 0, 0 );
}

LogService::~LogService(){
	SAFE_DELETE( emergency_ );
}

LogService* LogService::Instance(){
	if(! LogService_ )
		LogService_ = new LogService();
	
	return LogService_;
}

void LogService::Shutdown(){
	SAFE_DELETE( LogService_ );
}

int LogService::initialize( const char* env_file ){
	std::cout <<std::endl;
	std::cout <<"*** initialize log service : " <<env_file <<std::endl;		

	if( env_file )
		env_file_ = env_file;

	return setEnvironment();
}

CLog* LogService::get( const char* log_name ){
	LogContain::iterator itr = logs_.find( log_name );
	if( itr != logs_.end() )
		return (CLog*)itr->second;
	return emergency_;
}

int LogService::setEnvironment(){
	if(! env_file_.size() )
		return 0;

	TiXmlDocument doc( env_file_.c_str() );

	if( doc.LoadFile() == false ){
		int line = doc.ErrorRow();
		int col = doc.ErrorCol();

		return -1;
	}

	if( doc.Error() )
		return -1;
	
	TiXmlNode* node = 0;
	TiXmlElement* element = doc.RootElement();

	StringObj value;
	value = (char*)element->Value();
	if(! value.isEqualIgnLetterType("config") )
		return -1;

	node = element->FirstChild("log_info");

	StringObj name;
	StringObj file;
	StringObj dir;
	StringObj type;
	StringObj rotate;
	StringObj rotate_size;	

	for( node = node->FirstChild() ; node != 0 ; node = node->NextSibling()){
		node->ToElement();
		name = node->FirstChild("name")->FirstChild()->Value();			
		file = node->FirstChild("file")->FirstChild()->Value();
		dir = node->FirstChild("dir")->FirstChild()->Value();		
		type = node->FirstChild("type")->FirstChild()->Value();		
		rotate = node->FirstChild("rotate")->FirstChild()->Value();
		rotate_size = node->FirstChild("rotate_size")->FirstChild()->Value();

		char* dir_path = 0;
		char* file_name = 0;

		if( dir.toString() != "0" )
			dir_path = dir.toCharacters();

		if( file.toString() != "0" )
			file_name = file.toCharacters();

		CLog* log = new CLog( \
			type.to4ByteNumber(), \
			dir_path, \
			file_name, \
			rotate.to4ByteNumber(), \
			( rotate_size.to4ByteNumber() * 1024 ) \
		);
		
		logs_.insert( std::pair<std::string, CLog*>(name.toCharacters(), log) );

		std::cout <<"*** initialize log service entity " <<std::endl;
		std::cout <<"   name : " <<name.toCharacters() <<std::endl;
		std::cout <<"   path : " <<dir.toCharacters() <<" / " <<file.toCharacters() <<std::endl;		
		std::cout <<std::endl;
	}

	return 0;
}
